package com.example.auction.activity.mineActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.auction.R;
import com.example.auction.activity.ItemDetailsViewActivity;
import com.example.auction.sqlite.Sqlite;
import com.example.auction.util.MyUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//显示用户竞价过并且正在拍卖的物品
/*
 * 逻辑：
 * 通过user_id查询竞价表获得用户竞价过的item_id
 * 通过item_id显示item表获得物品行
 */
public class MineBiddingActivity extends AppCompatActivity {

    private ListView lv_mine_bidding_list;
    //图文列表适配器
    private SimpleAdapter simpleAdapter;
    //数据源的列表的类型是Map类型（键值对），Map<String（键名），Object（值的类型）>
    private List<Map<String, Object>> itemList;

    private Integer user_id;
    private Sqlite sqlite;
    private Cursor cursor1;
    private Bitmap imagebm;

    private TextView tv_list_none;
    private Integer item_id;
    private TextView tv_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_bidding);

        sqlite = new Sqlite(MineBiddingActivity.this);
        //绑定列表控件
        lv_mine_bidding_list = findViewById(R.id.lv_mine_bidding_list);
        tv_list_none = findViewById(R.id.tv_list_none);
        tv_back = findViewById(R.id.tv_back);

        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MineBiddingActivity.this.finish();
            }
        });

        //初始化数据
        initData();
        inAdapter();
    }

    private void inAdapter() {
        //初始化适配器
        simpleAdapter = new SimpleAdapter(
                MineBiddingActivity.this,
                //数据源
                itemList,
                //列表单个子项的布局文件
                R.layout.list_tablayout_home_kind_item,
                //键的名字，要跟map中的键名对应
                new String[]{"img", "name", "des", "tv_max_price", "max_price", "owner", "end_time", "item_id"},
                //把键名对应的值绑定到控件上，写控件的id
                new int[]{
                        R.id.home_item_list_img,
                        R.id.home_item_list_name,
                        R.id.home_item_list_des,
                        //当前最高价文本
                        R.id.tv_max_price,
                        //最高价数值
                        R.id.home_item_list_max_price,
                        R.id.home_item_list_owner,
                        R.id.home_item_list_endtime
                });

        //必须写这个才能显示图片
        simpleAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
            @Override
            public boolean setViewValue(View view, Object data, String textRepresentation) {
                if ((view instanceof ImageView) && (data instanceof Bitmap)) {
                    ImageView imageView = (ImageView) view;
                    Bitmap bitmap = (Bitmap) data;
                    imageView.setImageBitmap(bitmap);
                    return true;
                }
                return false;
            }
        });

        //装载适配器
        lv_mine_bidding_list.setAdapter(simpleAdapter);
        //设置子项点击监听
        lv_mine_bidding_list.setOnItemClickListener(new MineBiddingActivity.itemOnClick());
    }

    @SuppressLint("Range")
    private void initData() {
        user_id = getIntent().getExtras().getInt("user_id");

        //获取当前用户的竞价表
        cursor1 = sqlite.selectBid("user_id", user_id.toString());

        itemList = new ArrayList<>();

        //循环添加列表子项数据
        while (cursor1.moveToNext()) {
            //从竞价表获取item_id
            item_id = cursor1.getInt(cursor1.getColumnIndex("item_id"));
            Cursor cursor2 = sqlite.selectItemByState(
                    "item_id", item_id.toString(), "已通过", "endtime asc");

            //循环添加列表子项数据
            while (cursor2.moveToNext()) {
                //map用于暂时装载数据
                Map<String, Object> map = new HashMap<>();

                //获取物品id
                Integer item_id = cursor2.getInt(cursor2.getColumnIndex("item_id"));
                //根据id获取前图片
                imagebm = MyUtil.getImageBySQL(MineBiddingActivity.this, "item", item_id);

                //物品名
                String itemName = cursor2.getString(cursor2.getColumnIndex("item_name"));
                //描述
                String itemDes = cursor2.getString(cursor2.getColumnIndex("item_desc"));

                //我的出价文本
                String tv_max_price = "我的出价：";
                //我的出价数值
                String bidPrice = cursor1.getString(cursor1.getColumnIndex("bid_price"));

                //发布者名字
                Integer ownerID = 0;
                ownerID = cursor2.getInt(cursor2.getColumnIndex("owner_id"));
                String ownerName = MyUtil.getUserNameByID(MineBiddingActivity.this, ownerID);

                //截止时间
                String endTime = cursor2.getString(cursor2.getColumnIndex("endtime"));

                //打包键值对
                //图片数据库暂时还没做
                map.put("img", imagebm);
                map.put("name", itemName);
                map.put("des", itemDes);
                map.put("tv_max_price", tv_max_price);
                map.put("max_price", bidPrice);
                map.put("owner", ownerName);
                map.put("end_time", endTime);
                map.put("item_id", item_id.toString());

                //将子项加进列表
                itemList.add(map);

                tv_list_none.setVisibility(View.GONE);
            }
        }

    }

    //子项点击监听
    private class itemOnClick implements android.widget.AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String item_id = itemList.get(position).get("item_id").toString().trim();
            Toast.makeText(MineBiddingActivity.this, "您选择的是：" + item_id, Toast.LENGTH_SHORT).show();

            //将用户id以及点击的拍卖品名传给拍卖品竞价页
            Intent intent = new Intent();
            intent.putExtra("user_id", user_id);
            intent.putExtra("item_id", item_id);
            //传递从哪个页面跳转过去的信标
            intent.putExtra("from", "mineBidding");
            intent.setClass(MineBiddingActivity.this, ItemDetailsViewActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivityForResult(intent,1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1&&resultCode==100) {
            initData();
            inAdapter();
        }
    }
}